package server.client;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Vector;

import server.core.ServerDispatcher;

public class ClientSender extends Thread {

        private Vector<String> messageQueue;
        
        @SuppressWarnings("unused")
        private Client client;
        
        @SuppressWarnings("unused")
        private ServerDispatcher dispatcher;
        
        private PrintWriter writer;

        public ClientSender(Client client, ServerDispatcher dispatcher)
                        throws IOException {
                this.client = client;
                this.dispatcher = dispatcher;

                this.messageQueue = new Vector<String>();
                
                Socket socket = client.getSocket();
                this.writer = new PrintWriter(new OutputStreamWriter(
                                socket.getOutputStream()));
        }

        public synchronized void sendMessage(String message) {
                this.messageQueue.add(message);
                notify();
        }
        
        private synchronized String getNextMessageFromQueue() throws InterruptedException {
                while (this.messageQueue.size() == 0) {
                        wait();
                }
                
                String message = this.messageQueue.get(0);
                this.messageQueue.removeElementAt(0);
                
                return message;
        }
        
        private void sendMessageToClient(String message) {
                this.writer.println(message);
                this.writer.flush();
        }
        
        @Override
        public void run() {
                try {
                        while (!isInterrupted()) {
                                String message = getNextMessageFromQueue();
                                
                                sendMessageToClient(message);
                        }
                } catch (InterruptedException e) {
                        // Kommunikationsproblem
                }
        }
}
